<?php
/**
 * 微信自动登录
 */
namespace app\wechat\admin;

use app\common\controller\Wechat;
use app\system\model\SystemUser as UserModel;
use app\common\service\WechatUser;

class AutoLogin extends Wechat
{

    public function initialize() {
    	parent::initialize();
    }

    public function index(){
    	$userModel = new UserModel();
    	$wechatOauth = \We::WeChatOauth(config('wechat.'));

    	// 判断登陆
    	$login = $userModel->isLogin();
    	if (!isset($login['uid']) || !$login['uid']) {

    		try {
    			$accessTokenData = $wechatOauth->getOauthAccessToken();
    			$accessToken = $accessTokenData['access_token'];
    			$expiredTime = $accessTokenData['expires_in']+time();
    			$refreshToken = $accessTokenData['refresh_token'];
    			$openid = $accessTokenData['openid'];

    			// 创建用户或更新用户access_token
    			$wechatUserInfo = (new WechatUser())->getInfoByOpenid($openid, 'id,admin_id');
    			if (!$wechatUserInfo) {
    				$wechatUserData = $wechatOauth->getUserInfo($accessToken, $openid);
    				$insData = [
    					'openid' => $wechatUserData['openid'],
    					'nickname' => $wechatUserData['nickname'],
    					'sex' => $wechatUserData['sex'],
    					'province' => $wechatUserData['province'],
    					'city' => $wechatUserData['city'],
    					'country' => $wechatUserData['country'],
    					'avatar' => $wechatUserData['headimgurl'],
    					'subscribe' => 0,
    					'access_token' => $accessToken,
    					'expired_time' => $expiredTime,
    					'refresh_token' => $refreshToken,
    					'create_time' => time(),
    					'update_time' => time(),
    				];
    				db('wechat_user')->insertGetId($insData);

    				throw new \Exception('未绑定管理员账户');
    			} else {
    				$upData = [
    					'access_token' => $accessToken,
    					'expired_time' => $expiredTime,
    					'refresh_token' => $refreshToken,
    					'update_time' => time(),
    				];
    				db('wechat_user')->where('id', $wechatUserInfo['id'])->update($upData);

    				if ($wechatUserInfo['admin_id'] == 0) {
    					throw new \Exception('未绑定管理员账户');
    				}
    				$userName = db('system_user')->where('id', $wechatUserInfo['admin_id'])->value('username', '');
    				$res = $userModel->login($userName, 'autologin', 1);
    				if (!$res) {
    					throw new \Exception($userModel->getError());
    				}

    				session('wechat_user', db('wechat_user')->where('id', $wechatUserInfo['id'])->findOrEmpty());
    			}

    		} catch (\Exception $e) {
    			return $this->_error($e->getMessage());
    		}
    	}

    	// 跳转进入功能页
    	$params = request()->param();
    	$uri = arrayGet($params, 'u', '');
    	unset($params['u'], $params['nsukey'], $params['code'], $params['state']);
    	$queryString = http_build_query($params);
    	$url = url($uri).($queryString?'?'.$queryString:'');
    	header("Location: {$url}");
    	exit;
    }

    /**
     * 错误输出
     *
     * @author King
     * @date 2020年8月19日
     *
     * @param string $msg
     */
    private function _error($msg) {
		return $this->assign('msg', $msg)->fetch('/error');
    }
}